﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Manager;
using Model;
using System.Data;
using ExtAspNet;
using Manager.CustomerHelper;
namespace HealthSystem.sysAdmin
{
    public partial class CtityAdminManager : BasePage
    {
        HW_Manger_Admin_UserManager manager = new HW_Manger_Admin_UserManager();
        public override ModuleType Module
        {
            get
            {
                return ModuleType.SchoolManager;
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            Initialize();
            if (!IsPostBack)
            {
                ViewState["event"] = string.Empty;
                BindGrid();
            }
            
        }
        protected void BindGrid()
        {
            string susertype = usertype.SelectedValue;
            DataTable list = null;
            string saction = ViewState["event"] as string;
            Grid1.AllowPaging = true;
            Grid1.IsDatabasePaging = true;
            int count = 0;
            switch (susertype)
            {
                case "a":
                    if (string.IsNullOrEmpty(saction))
                    {
                        list = manager.SearchRole(Grid1.PageIndex,Grid1.PageSize,out count,1002,null);
                    }
                    else
                    {
                        list = manager.SearchRole(Grid1.PageIndex, Grid1.PageSize, out count, 1002, triggSearch.Text.Trim());
                    }
                    break;
                case "b":
                    if (string.IsNullOrEmpty(saction))
                    {
                        list = manager.SearchRole(Grid1.PageIndex,Grid1.PageSize,out count,1003,null);
                    }
                    else
                    {
                        list = manager.SearchRole(Grid1.PageIndex, Grid1.PageSize, out count, 1003, triggSearch.Text.Trim());
                    }
                    break;
                case "c":
                    if (string.IsNullOrEmpty(saction))
                    {
                        list = manager.SearchRole(Grid1.PageIndex,Grid1.PageSize,out count,1011,null);
                    }
                    else
                    {
                        list = manager.SearchRole(Grid1.PageIndex, Grid1.PageSize, out count, 1011, triggSearch.Text.Trim());
                    }
                    break;
                case "d":
                    if (string.IsNullOrEmpty(saction))
                    {
                        list = manager.SearchRole(Grid1.PageIndex,Grid1.PageSize,out count,1012,null);
                    }
                    else
                    {
                        list = manager.SearchRole(Grid1.PageIndex, Grid1.PageSize, out count, 1012, triggSearch.Text.Trim());
                    }
                    break;
                default:
                    if (string.IsNullOrEmpty(saction))
                    {
                        list = manager.SearchRole(Grid1.PageIndex, Grid1.PageSize, out count,0,null);
                    }
                    else
                    {
                        list = manager.SearchRole(Grid1.PageIndex, Grid1.PageSize, out count, 0, triggSearch.Text.Trim());
                    }
                    break;
            }
            Grid1.RecordCount = count;
            this.Grid1.DataSource = list;
            this.Grid1.DataBind();
           
        }
        protected void btnNew_Click(object sender, EventArgs e)
        {
            ExtAspNet.PageContext.RegisterStartupScript(Window1.GetShowReference("CityAdmin_new.aspx","新增管理员"));
        }
        protected void Window1_Close(object sender, ExtAspNet.WindowCloseEventArgs e)
        {
            BindGrid();
        }
        protected void usertype_Changed(object sender, EventArgs e)
        {
            Grid1.PageIndex = 0;
            ViewState["event"] = string.Empty;
            BindGrid();
        }
        protected void PageIndex_Changed(object sender, ExtAspNet.GridPageEventArgs e)
        {
            Grid1.PageIndex = e.NewPageIndex;
            BindGrid();
        }
        protected void triggSearch_Click(object sender, EventArgs e)
        {
            Grid1.PageIndex = 0;
            if (string.IsNullOrEmpty(triggSearch.Text))
            {
                ViewState["event"] = string.Empty;
            }
            else
            {
                ViewState["event"] = "search";
            }
            BindGrid();
        }
        protected void btnExport_Click(object sender, EventArgs e)
        {
            string saction = ViewState["event"].ToString();
            string susertype = usertype.SelectedValue;
            string searchstring = HttpUtility.UrlEncode(triggSearch.Text.Trim());
            string url = "ExportAdmin.aspx?saction=" + saction + "&susertype=" + susertype + "&searchstring=" + searchstring;
           
            PageContext.RegisterStartupScript(Window2.GetShowReference(url, ""));

          
        }
        protected void Grid1_RowCommand(object sender, ExtAspNet.GridCommandEventArgs e)
        {
            try
            {
                string username = Grid1.Rows[e.RowIndex].DataKeys[1].ToString();
                if (e.CommandName == "delete")
                {
                    manager.DeleteById(username);
                    BindGrid();

                }
                if (e.CommandName == "reset")
                {
                    //重置密码
                    HW_Manger_Admin_UserManager adminUserManager = new HW_Manger_Admin_UserManager();
                    string showpass=SecrityPass.CreatePassword(6);
                    string pass=SecrityPass.GetPassword(showpass);
                    //string pass = System.Configuration.ConfigurationManager.AppSettings["default"].ToString();
                    adminUserManager.ResetPassWord(username, showpass, pass);
                    Alert.Show("密码重置成功");
                    BindGrid();
                }
            }
            catch
            {
                Alert.Show("操作失败!");
            }
        }
        public void Initialize()
        {
            if (CustomerProfile.RoleId == 1001)
            {
                ExtAspNet.LinkButtonField link = new LinkButtonField();
                link.HeaderText = "重置密码";
                link.Text = "重置密码";
                link.CommandName = "reset";
                link.ConfirmText = "你确定要重置密码";
                Grid1.Columns.Add(link);

                ExtAspNet.WindowField winfiled = new WindowField();
                winfiled.WindowID = "Window1";
                winfiled.HeaderText = "修改资料";
                winfiled.Icon = ExtAspNet.Icon.Pencil;
                winfiled.DataIFrameUrlFields = "XX_UserName";
                winfiled.DataIFrameUrlFormatString = "~/Cityadmin_Edit.aspx?id={0}";
                winfiled.DataWindowTitleField = "XX_UserName";
                winfiled.DataWindowTitleFormatString = "编辑 - {0}";
                Grid1.Columns.Add(winfiled);
            }
        }
        //dataset导出EXCEL
        public void CreateExcel(DataTable dt, string strFile, string strExt)
        {
            string strAppType = "";

            switch (strExt)
            {

                case "xls":

                    strAppType = "application/ms-excel";

                    break;

                case "doc":

                    strAppType = "application/ms-word";

                    break;

                case "txt":

                    strAppType = "application/ms-txt";

                    break;

                case "html":

                case "htm":

                    strAppType = "application/ms-html";

                    break;

                default: return;

            }

            GridView MyGridView = new GridView();

            MyGridView.DataSource = dt;

            MyGridView.DataBind();

            HttpContext.Current.Response.Clear();

            HttpContext.Current.Response.Buffer = true;

            HttpContext.Current.Response.AddHeader("Content-Type", "text/html; charset=GB2312");

            HttpContext.Current.Response.AppendHeader("Content-Disposition", string.Format("attachment;filename={0}.{1}", HttpUtility.UrlEncode(strFile,System.Text.Encoding.GetEncoding("GB2312")), strExt));

            HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");

            HttpContext.Current.Response.ContentType = strAppType;

            //MyGridView.Page.EnableViewState = false;

            //二、定义一个输入流

            System.Globalization.CultureInfo myCItrad = new System.Globalization.CultureInfo("ZH-CN", true);

            System.IO.StringWriter oStringWriter = new System.IO.StringWriter(myCItrad);

            System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);

            //三、将目标数据绑定到输入流输出

            MyGridView.RenderControl(oHtmlTextWriter);

            HttpContext.Current.Response.Write(oStringWriter.ToString());

            HttpContext.Current.ApplicationInstance.CompleteRequest();

          
        }
        protected void export_click(object sender, EventArgs e)
        {
            Response.ClearContent();
            Response.AddHeader("content-disposition", "attachment; filename=MyExcelFile.xls");
            Response.ContentType = "application/excel";
            Response.Write(GetGridTableHtml(Grid1));
            Response.End();
        }
        private string GetGridTableHtml(Grid grid)
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();

            sb.Append("<table cellspacing=\"0\" rules=\"all\" border=\"1\" style=\"border-collapse:collapse;\">");

            sb.Append("<tr>");
            foreach (GridColumn column in grid.Columns)
            {
                sb.AppendFormat("<td>{0}</td>", column.HeaderText);
            }
            sb.Append("</tr>");


            foreach (GridRow row in grid.Rows)
            {
                sb.Append("<tr>");
                foreach (object value in row.Values)
                {
                    string html = value.ToString();
                    // 处理CheckBox
                    if (html.Contains("box-grid-static-checkbox"))
                    {
                        if (html.Contains("box-grid-static-checkbox-uncheck"))
                        {
                            html = "×";
                        }
                        else
                        {
                            html = "√";
                        }
                    }

                    // 处理图片
                    if (html.Contains("<img"))
                    {
                        string prefix = Request.Url.AbsoluteUri.Replace(Request.Url.AbsolutePath, "");
                        html = html.Replace("src=\"", "src=\"" + prefix);
                    }

                    sb.AppendFormat("<td>{0}</td>", html);
                }
                sb.Append("</tr>");
            }

            sb.Append("</table>");

            return sb.ToString();
        }

    }
}